package me.feng.servlet
import java.util.logging.Logger
import org.apache.catalina.websocket.StreamInbound
import org.apache.catalina.websocket.WebSocketServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.annotation.WebServlet
import me.feng.messageinbound.MainChart
import akka.actor.ActorSystem
import akka.actor.ActorRef
import me.feng.entity.User
import java.util.UUID
import akka.actor.actorRef2Scala
import me.feng.actors.MainActor
import me.feng.domain.Member
import me.feng.dao.impl.MemberDao
import me.feng.service.MemberService

@WebServlet(Array("/main.ws"))
class MainServlet extends WebSocketServlet {

  // Log
  private val logger = Logger.getLogger(classOf[MainServlet].getName());

  var uid: String = _

  var name: String = _

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) {
    uid = req.getParameter("uid")
    //uid = UUID.randomUUID().toString().replace("-", "")
    if (req.getCookies()!=null) {
      val sid = for {
        c <- req.getCookies()
        if c != null && c.getName().equals("sid")
      } yield c.getValue()
      if (sid != null && sid.length > 0 && req.getSession().getId().equals(sid.head)) {
        super.doGet(req, resp)
      }
    }

  }

  override def createWebSocketInbound(subProtocol: String, request: HttpServletRequest): StreamInbound = {
    println(uid)
    //OschartContext.getMainActor.!(chart)
    val m = new MemberService().getMemberbyUid(uid)
    val u = User.member2User(m)
    val main = request.getServletContext().getAttribute("mainActor").asInstanceOf[ActorRef]
    val akka = request.getServletContext().getAttribute("akka").asInstanceOf[ActorSystem]
    val chart = new MainChart(MainActor.DEFAULT_MAIN_ID, akka, main)
    chart.setUser(u)
    main ! (uid -> chart)
    chart
  }

}
